from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from django.shortcuts import render
from django.http import JsonResponse as Response
from django.shortcuts import HttpResponse
from django.contrib import auth
from rest_framework.views import APIView
from .serializers import UserSerializer


class Login(APIView):
    def post(self, request):
        receive = request.data
        if request.method == 'POST':
            username = receive['username']
            password = receive['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # 更新token值
                
                token = Token.objects.get(user=user)
                token.delete()
                token = Token.objects.create(user=user)
                user_info = User.objects.get(username=user.username)
                serializer = UserSerializer(user_info, context={'request': request})
                response = serializer.data
                # response['token'] = token.key
                #get_user_dict(user, response)
                return Response({
                    "code": 20000,
                    token.key: response,  # response contain user_info and token
                })
            else:
                try:
                    User.objects.get(username=username)
                    cause = '密码错误'
                except User.DoesNotExist:
                    cause = '用户不存在'
                return Response({
                    "result": 0,
                    "cause": cause,
                })
